<?php
class UsersController extends AppController {
	var $name = 'Users';
	var $uses = array('User', 'Position', 'Department');
	
	function index() {
		$this->set('users', $this->User->find('all'));
		
	}
	
	function view($id = null) {
		$this->User->id = $id;
		$this->set('user', $this->User->read());
	}
	
	function add() {
		if (empty($this->data)) {
			$this->set('department_id', $this->Department->find('list'));
			$this->set('position_id', $this->Position->find('list'));
		} else {
			if ($this->User->save($this->data)) {
				$this->flash('You have successfully added a user.', '/users');
			}
		}
	}
	
	function edit($id) {
		$this->User->id = $id;
		if (empty($this->data)) {
			$this->data = $this->User->read();
			$this->set('position_id', $this->Position->find('list'));
		}
		else {
			if ($this->data['User']['password'] == ''){
				$saved = $this->User->save($this->data, true, array('firstName', 'lastName', 'email', 'position_id'));
				$this->flash('The user information has been updated.', '/users');			 
			}
			else {
				$this->data['User']['password'] = Security::hash($this->data['User']['password'], 'md5');
				$saved = $this->User->save($this->data);
				$this->flash('The user information and password has been updated.', '/users');
			}
		}
	}
	
	function disable($id) {
		$this->User->id = $id;
		$this->User->saveField('enabled', '0');		
		
		$this->redirect(array('controller' => 'users', 'action' => 'index'));
	}
	
	function enable($id) {
		$this->User->id = $id;
		$this->User->saveField('enabled', '1');
		
		$this->redirect(array('controller' => 'users', 'action' => 'index'));
	}
	
	function delete($id) {
		$this->User->del($id);
		$this->flash('The user has been deleted.', '/users');
	}
}
?>